package org.mcjug.model;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class StatusProvider extends ContentProvider {
	public static String TAG = StatusData.class.getSimpleName();
	public static final Uri CONTENT_URI = Uri
			.parse("content://org.mcjug.yamba.statusprovider");
	public static final String SINGLE_RECORD_MIME_TYPE = "vnd.android.cursor.item/vnd.mcjug.yamba.status";
	public static final String MULTIPLE_RECORDS_MIME_TYPE = "vnd.android.cursor.dir/vnd.mcjug.yamba.mstatus";
	StatusData statusData;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return statusData.delete(getId(uri), selection, selectionArgs);
	}

	@Override
	public String getType(Uri uri) {
		if (getId(uri) < 0) {
			return MULTIPLE_RECORDS_MIME_TYPE;
		} else {
			return SINGLE_RECORD_MIME_TYPE;
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long id = statusData.insertOrIgnore(values);
		if (id == -1) {
			throw new RuntimeException(String.format(
					"%s: Failed to insert [%s] to [%s] for unknown reasons.",
					TAG, values, uri)); // 3
		} else {
			return ContentUris.withAppendedId(uri, id); // 4
		}

	}

	@Override
	public boolean onCreate() {
		statusData = new StatusData(getContext());
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		return statusData.query(getId(uri), projection, selection,
				selectionArgs, sortOrder);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return statusData.update(getId(uri), values, selection, selectionArgs);
	}

	private long getId(Uri uri) {
		String lastPathSegment = uri.getLastPathSegment();
		if (lastPathSegment != null) {
			try {
				return Long.parseLong(lastPathSegment);
			} catch (NumberFormatException e) {
			}
		}
		return -1;
	}
}
